//
//  LJFMyController.m
//  SevenZhou
//
//  Created by qianfeng on 15/9/14.
//  Copyright (c) 2015年 ljf. All rights reserved.
//

#import "LJFMyController.h"
#import "LJFMySevenCell.h"
#import "LJFMySevenModel.h"
#import "LJFLoginHeadView.h"
#import "LJFVLoginOrRegisterController.h"
#import "LJFMySetController.h"
#import "LJFHttpManager.h"
#include "Connector.h"
#import "LJFNumberDataController.h"

@interface LJFMyController ()<UITableViewDataSource,UITableViewDelegate,LoginSuccessDelegate,MySetDelegate,loginSuccessHeadViewDelegate>
{
    NSMutableArray *_dataArr;
    
    NSDictionary *_successDict;
    
    LJFLoginHeadView *_Loginhead;
    
    BOOL _isLogining;
}


@property (weak, nonatomic) IBOutlet UITableView *mytableView;

@property (weak, nonatomic) IBOutlet UIImageView *head_img;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableContantY;

@end

@implementation LJFMyController

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self)
    {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //[self settableViewFrame];
    self.view.backgroundColor = [UIColor  whiteColor];
    
    [self isLogin];
    
    [self headImgAddTap];
    
    [self loadTableData];

}

- (void)isLogin
{
    NSUserDefaults *myDefault = [NSUserDefaults standardUserDefaults];
    NSString *isLogin = [myDefault objectForKey:@"isLogin"];
    
    if ([isLogin isEqualToString:@"YES"])
    {
        NSString *name = [myDefault objectForKey:@"name"];
        NSString *password = [myDefault objectForKey:@"passWord"];
        
        [self beginLoginWithName:name andPassWord:password];
    }
    else
    {
        _isLogining = NO;
    }
}

- (void)beginLoginWithName:(NSString *)name andPassWord:(NSString *)passWord
{
    LJFHttpManager *manager = [LJFHttpManager shareInstance];
    
    NSString *urlStr = [NSString stringWithFormat:URL_LOGIN_parmater ,name,passWord];
    
    [manager getDataFromNetWithUrl:URL_LOGIN AndParameterStr:urlStr success:^(id responseObj)
     {
         
         NSNumber *num = responseObj[@"status"][@"succeed"];
         
         int succeed = [num intValue];
         
         if (succeed == 0)
         {
             UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:responseObj[@"status"][@"error_desc"] delegate: self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [alter show];
             
             _isLogining = NO;
             
         }else if (succeed == 1)
         {
             _successDict = responseObj[@"data"];
             
             [self createLoginSuccessHeadViewWithDictionary:responseObj[@"data"]];
             
             _isLogining = YES;
         }
         
     } failure:^(NSError *error)
     {
         NSLog(@"error == %@",error);
         
         _isLogining = NO;
         
     }];

}

- (void)headImgAddTap
{
    _head_img.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(login)];
    
    [_head_img addGestureRecognizer:tap];
}

- (void)login
{
    [self loginOrRegister:nil];
}

//加载数据
- (void)loadTableData
{
    NSArray *titleArr = @[@[@"我的订单",@"待评论项目",@"出游凭证",@"购物车",@"我的收藏",@"我的反馈"],@[@"我的资料",@"我的等级",@"我的勋章",@"我的红包"],@[@"关于七洲",@"联系我们",@"设置"]];
    NSArray *imgArr = @[@[@"ic_action_order",@"ic_action_modify_order",@"visit_passport_1",@"ic_action_shopping_cart_green",@"my_collect",@"ic_action_feedback"],@[@"ic_action_datum",@"ic_action_grade",@"ic_action_medal",@"my_balance"],@[@"ic_action_about_us",@"ic_action_contact_us",@"ic_action_set"]];
    NSArray *subTitleArr = @[@[@"查看详细订单",@"0",@"0",@"0",@"0",@""],@[@"",@"绿卡会会员俱乐部",@"",@""],@[@"",@"",@""]];
    
    for (int i =0; i < 3; i++)
    {
        NSArray *title1 = titleArr[i];
        NSArray *img1 = imgArr[i];
        NSArray *sub1 = subTitleArr[i];
        
        NSMutableArray *arrM = [[NSMutableArray alloc] init];
        
        for (int j = 0 ; j < title1.count; j++)
        {
            LJFMySevenModel *model = [[LJFMySevenModel alloc] init];
            model.imgName = img1[j];
            model.name = title1[j];
            model.subtitle =sub1[j];
            
            if ([sub1[j] length]>0)
            {
                model.isShowGoImg = NO;
            }
            else
            {
                model.isShowGoImg = YES;
            }
            
            [arrM addObject:model];
        }
        
        [_dataArr addObject:arrM];
    }
    
    [_mytableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createLoginSuccessHeadViewWithDictionary:(NSDictionary *)dict
{
    _Loginhead = [[NSBundle mainBundle] loadNibNamed:@"LJFLoginHeadView" owner:self options:0][0];
    _Loginhead.frame = CGRectMake(0, 64, self.view.frame.size.width, 170);
    _Loginhead.dict =dict;
    _Loginhead.mydelegate = self;
    [self.view addSubview:_Loginhead];
}


- (IBAction)loginOrRegister:(id)sender
{
    LJFVLoginOrRegisterController *login = [self.storyboard instantiateViewControllerWithIdentifier:@"LJFVLoginOrRegisterController"];
    login.mydelegate = self;
    [self presentViewController:login animated:YES completion:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -loginSuccessHeadViewDelegate

- (void)loginHeadViewGetNumberData:(LJFLoginHeadView *)headView
{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.4;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromRight;
    [self.view.window.layer addAnimation:animation forKey:nil];
    
    
    LJFNumberDataController *number = [self.storyboard instantiateViewControllerWithIdentifier:@"LJFNumberDataController"];
    
   [self presentViewController:number animated:NO completion:nil];
    
}

#pragma mark - LoginSuccessDelegate

- (void)LoginSuccess:(LJFVLoginOrRegisterController *)controll successDictionary:(NSDictionary *)dict
{
    NSLog(@"dict == %@",dict);
    
    _successDict = dict;
    
    [self createLoginSuccessHeadViewWithDictionary:dict];
    
    _isLogining = YES;
}

#pragma mark -UITableViewDataSource,UITableViewDelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *arr = _dataArr[section];
    
    return arr.count;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSArray *arr = _dataArr[indexPath.section];
    
    LJFMySevenModel *model = arr[indexPath.row];
    
    LJFMySevenCell *cell=[tableView dequeueReusableCellWithIdentifier:@"LJFMySevenCell"];
    
    cell.imgView.image = [UIImage imageNamed:model.imgName];
    cell.title.text = model.name;
    cell.subtitle.text = model.subtitle;
    cell.Goimg.hidden = model.isShowGoImg;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section != 0)
    {
        return 20;
    }
    else
    {
        return 0;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self didselectedSwitchWith:indexPath];
}

- (void)didselectedSwitchWith:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2 || (indexPath.section == 0 && indexPath.row == 2))
    {
        if (indexPath.section == 2 && indexPath.row == 2)
        {

            
            LJFMySetController *set = [self.storyboard instantiateViewControllerWithIdentifier:@"LJFMySetController"];
            set.mydelegate = self;
            set.nameStr = _successDict[@"user"][@"name"];
            
            [self presentViewController:set animated:YES completion:nil];
        }
    }
    else
    {
        if (!_isLogining)
        {
            [self loginOrRegister:nil];
        }
    }
}

#pragma mark -MySetDelegate

- (void)MySetdidRegisterIDWithController:(LJFMySetController *)set
{
    [_Loginhead removeFromSuperview];
    _Loginhead = nil;
    _successDict = [NSDictionary dictionary];
    _isLogining = NO;
    
    NSUserDefaults *mydefaults = [NSUserDefaults standardUserDefaults];
    [mydefaults setObject:@"NO" forKey:@"isLogin"];
    [mydefaults synchronize];
}

- (void)MySetdidLoginIDWithController:(LJFMySetController *)set WithSuccessData:(NSDictionary *)dict
{
    _successDict = dict;
    
    [self createLoginSuccessHeadViewWithDictionary:dict];
    
    _isLogining = YES;

}


@end
